import os
import shutil
import json
from PIL import Image

# 设定读取目录为当前目录下的c1文件夹
read_folder = os.path.join(os.path.dirname(__file__), 'c1')

# 设定输出目录为当前目录下的eff文件夹
eff_folder = os.path.join(os.path.dirname(__file__), 'eff')

# 创建输出文件夹
os.makedirs(eff_folder, exist_ok=True)


# 遍历读取目录下的文件
eff_data = {}
for filename in os.listdir(read_folder):
    # 读取json文件
    if filename.endswith('.json'):
    # if filename == '0088.json':
        json_path = os.path.join(read_folder, filename)
        # 读取json文件内容
        with open(json_path, 'r') as f:
            data = json.load(f)
            # 获取json文件名
            json_name = os.path.splitext(filename)[0]
             # 创建输出文件夹
            output_folder = os.path.join(eff_folder, json_name)
            if not os.path.exists(output_folder):
                os.makedirs(output_folder)
            # 遍历'mc'键下的数据
            res_length = 0
            frame_rate = 0
            for key in data['mc']:
                # 获取帧数据
                frames = data['mc'][key]['frames']
                # 查找图片文件
                for img_filename in os.listdir(read_folder):
                    if json_name in img_filename and img_filename.endswith(".png"):
                        img_path = os.path.join(read_folder, img_filename)
                        print(f"图片文件 {img_path} 存在")
                        # 打开图片文件
                        img = Image.open(img_path)
                        try:
                            # 遍历帧数据
                            for i, frame in enumerate(frames):
                                res = frame['res']
                                x = data['res'][res]['x']
                                y = data['res'][res]['y']
                                w = data['res'][res]['w']
                                h = data['res'][res]['h']
                                # 检查裁剪区域的坐标
                                if x < 0 or y < 0 or x + w > img.width or y + h > img.height:
                                    print(f"错误：裁剪区域超出了图片的边界。x={x}, y={y}, w={w}, h={h}")
                                else:
                                    # 裁剪图片
                                    cropped_img = img.crop((x, y, x + w, y + h))
                                    # 保存裁剪后的图片
                                    output_path = os.path.join(output_folder, f"{i}.png")
                                    cropped_img.save(output_path)
                        except Exception as e:
                            print(f"错误：{e}")
                        finally:
                            # 关闭图片文件
                            img.close()
                            res_length = len(data['res'])
                            frame_rate = data['mc'][key]['frameRate']
                        break
                else:
                    print(f"图片文件 {json_name} 不存在")
                eff_data[json_name] = {'resLength': res_length, 'frameRate': frame_rate}

# 保存eff.json文件
with open(os.path.join(eff_folder, 'eff.json'), 'w') as f:
    json.dump(eff_data, f, indent=4)